package com.thingple.rodbell.packet;

import android.util.Log;

import com.thingple.util.Bytes;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 异步数据流buffer, 接收数据流并缓存到队列里, 需要使用的时候从队列里取出
 */
public class AsyncBuffer {

    private static final String TAG = AsyncBuffer.class.getName();

    protected boolean debug;

    protected final Queue<byte[]> q = new LinkedBlockingQueue<>(1024);

    protected final PacketBuffer buf = new PacketBuffer(24 * 1024);

    public void onReceiveData(byte[] packet) {
        if (debug) {
            Log.d(TAG, "packet:" + Bytes.ByteToHexString(packet));
        }
        q.add(packet);
    }

    /**
     * 填充buf, 从队列里拉取一个数据包到buf里(如果没数据就不执行)
     */
    protected void prepareRaw() {

        byte[] bytes = q.poll();
        if (bytes == null) {
            return;
        }
        for (byte b : bytes) {
            buf.offer(b);
        }
    }
    public void setDebug(boolean enable) {
        debug = enable;
    }
}
